package app.auto.runner.base.intf.json;

/**
 * Createdby87716on2017/3/3.
 */

import android.text.TextUtils;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import app.auto.runner.base.ActivityStack;
import app.auto.runner.base.ActivityUtil;
import app.auto.runner.base.intf.ListBuilder;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.ShareAlert;

public class JsonToMapUtils {

    public static String filterJson(String json) {
        return filterJsonPrivate(json);
    }

    private static String filterJsonPrivate(String json) {
        json = json.replace("\"[", "[").replace("]\"", "]").replaceAll("\"\\{", "{").replaceAll("\\}\"", "}");
        return json;
    }

    public static Map<String, Object> parseJsonToMap(String jsonStr) {
        return parseJsonToMap(jsonStr, false);
    }

    /**
     * 日志文件生成器
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> parseJsonToMap(String jsonStr, boolean sequence) {
        return parseJsonToMapPrivate(jsonStr, sequence);
    }

    private static Map<String, Object> parseJsonToMapPrivate(String jsonStr, boolean sequence) {
        MapBuilder map = MapBuilder.build();
        if (sequence) {
            map = map.sequnIndices();
        }
//        Map map = new HashMap();
        //最外层解析
        JSONObject json = null;
        try {
            try {
//                jsonStr = jsonStr
//                        .replaceAll("\\\\", "")
//                        .replaceAll("\"\\[", "[").replaceAll("]\"", "]")
//                        .replace("\"{", "{").replace("}\"", "}");
            } catch (Exception e) {
                ShareAlert.shareAlert(ActivityStack.publicactivity, e.getCause() + " \n\n " + e.getMessage() + "\n\n");
//                    jsonStr.substring(860));
            }
//            if (TextUtils.isEmpty(jsonStr)) {
//                return map.get();
//            }
            json = new JSONObject(jsonStr);

            for (int i = 0; i < json.names().length(); i++) {
                String k = json.names().getString(i);
                Object v = json.get(k);

                //如果内层还是数组的话，继续解析
//                if (v.toString().startsWith("\"") && v.toString().endsWith("\"")) {
//                    if (v.toString().startsWith("\"[")) {
//                        List list = jsontoList(v.toString().substring(1, v.toString().length() - 1));
//                        map.put(k, list);
//                    }
//                }
                if (v instanceof JSONArray) {

                    List list = JsonToMapUtils.jsontoList(((JSONArray) v).toString());
                    map.add(k.toString(), list);
                } else
//                else

                {
                    map.add(k.toString(), v);
                }
            }
        } catch (JSONException e) {
//            ShareAlert.shareAlert(ActivityStack.publicactivity, e.getCause()+" \n\n "+e.getMessage()+"\n\n"+
//                    jsonStr.substring(860));
            e.printStackTrace();
        }
        return map.get();
    }

    public static String objectToJson(Object obj) {
        if (obj instanceof Map) {
            return mapToJson((Map<String, String>) obj);
        } else if (obj instanceof List) {
            return listtoJson((List) obj);
        }
        return obj.toString();
    }

    public static String mapToJson(Map<String, String> map) {
        return mapToJsonPrivate(map);
    }

    private static String mapToJsonPrivate(Map<String, String> map) {
        Set<String> keys = map.keySet();
        String key = "";
        Object value = "";
        StringBuffer jsonBuffer = new StringBuffer();
        jsonBuffer.append("{");
        for (Iterator<String> it = keys.iterator(); it.hasNext(); ) {
            key = (String) it.next();
            value = map.get(key);
            String json = "";
            if (value instanceof List) {
                json = listtoJson((List) value);

            } else if (value instanceof Map) {
                json = mapToJson(((Map) value));
            } else {
                json = "\"" + value + "\"";
            }
            jsonBuffer.append("\"" + key + "\"" + ":" + json);
            if (it.hasNext()) {
                jsonBuffer.append(",");
            }
        }
        jsonBuffer.append("}");
        return jsonBuffer.toString().replaceAll("\"\\{", "{").replaceAll("\\}\"", "}");
    }

    public static String listtoJson(List value) {
        return listtoJson(value, false);
    }

    private static String listtoJson(List value, boolean isjson) {
        return listtoJsonPrivate(value, isjson);
    }

    private static String listtoJsonPrivate(List value, boolean isjson) {
        ListBuilder listBuilder = ListBuilder.build();

        String json;
        String m = "";
        for (Object o : value) {

            if (o instanceof Map || o instanceof List) {
                m = mapToJson((Map) o);
            } else {
                m = o.toString();
            }
            listBuilder.add(m);
        }
        json = listBuilder.get().toString();
        if (!isjson) {
            json = json.
                    replace("\"[", "[").replace("]\"", "]");
        }

        return json;
    }

    private static Gson gson = new Gson();

    public static String entityToJson(Object src) {
        return gson.toJson(src);
    }

    public static List jsontoList(String json) {
        return jsontoListPrivate(json);
    }

    private static List jsontoListPrivate(String json) {
        try {
            if (TextUtils.isEmpty(json)) {
                return new ArrayList();
            }
//            json = json.replaceAll("\\\\", "")
//                    .replaceAll("\"\\[", "[").replaceAll("]\"", "]")
//                    .replace("\"{", "{").replace("}\"", "}");

            JSONArray array = new JSONArray(json);
            ListBuilder lb = ListBuilder.build();
            if (array == null) {
                return new ArrayList();
            }
            for (int i = 0; i < array.length(); i++) {
                if (array.getString(i).toString().contains("{")) {
                    lb.add(JsonToMapUtils.parseJsonToMap(array.getString(i)));

                } else if(array.getString(i).toString().contains("[")) {
                    lb.add(JsonToMapUtils.jsontoList(array.getString(i)));

                }else {
                        lb.add(array.getString(i));
                }
            }
            return lb.get();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return new ArrayList();
    }
}  